package com.shopoo.authorization.domain.configurers;

import java.io.IOException;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 *
 * @Author <a href="mailto:android_li@sina.cn">MaoYuan.Li</a>
 * @Date 2023/3/19 08:47
 */
public class JwtTokenFilter extends OncePerRequestFilter {
	private final JwtDecoder jwtDecoder;

	public JwtTokenFilter(JwtDecoder jwtDecoder) {
		this.jwtDecoder = jwtDecoder;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 获取请求头中的Authorization信息
		String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

		// 解析Authorization信息获取JWT Token
		if (StringUtils.hasText(authorizationHeader) && authorizationHeader.startsWith("Bearer ")) {
			String jwtToken = authorizationHeader.substring(7);
			Jwt jwt = jwtDecoder.decode(jwtToken);
			String username = jwt.getSubject();
			System.out.println(username);
//			UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, );
//			if (jwtTokenProvider.validateToken(jwtToken)) {
//				// 将JWT Token存储在SecurityContext中
//				Authentication authentication = jwtTokenProvider.getAuthentication(jwtToken);
//				SecurityContextHolder.getContext().setAuthentication(authentication);
//			}
		}

		// 继续执行过滤器链
		filterChain.doFilter(request, response);
	}
}
